/*
 * @Author: your name
 * @Date: 2020-12-14 16:37:50
 * @LastEditTime: 2021-06-12 14:57:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \qdBillingSystem\src\router\index.js
 */
/* eslint-disable */
import Vue from 'vue'
import VueRouter from 'vue-router'
import { routers } from './router'
import { Loading } from 'element-ui'
import store from '../store/index'
// 路由重复点击报错处理
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch((err) => err)
}
// 路由重复点击报错处理

// 决绝登录页面报login路由错误
Vue.use(VueRouter)
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
	return originalReplace.call(this, location).catch((err) => err)
}

const routerConfig = {
	mode: '',
	linkActiveClass: 'active',
	routes: routers,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition
		} else {
			return { x: 0, y: 0 }
		}
	},
}

const router = new VueRouter(routerConfig)

let loading
router.beforeEach((to, form, next) => {
	const token = store.state.token
	if(token == 'null' && to.path != '/login'){
		next({
			path: '/login',
			replace: true,
		})
	}
	if (!to.matched.length) {
		next({
			path: '/error/404',
			replace: true,
		})
	} else {
		document.title = to.meta.title || admin
		// next();
		let token = sessionStorage.getItem('token')
		if (to.matched.some((record) => record.meta.requireAuth)) {
			// 判断该路由是否需要登录权限
			if (token) {
				// 判断当前的token是否存在
				next()
			} else {
				next({
					path: '/login',
					query: { redirect: to.fullPath, type: 0 }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
				})
			}
		} else {
			next()
		}
	}
})
router.afterEach((to, from) => {
	// 解决某些情况下loading无法关闭的情况
	// loading.close();
})

export default router
